<template>
  <div>
    <input type="file" @change="handleFileChange" accept=".pdf" />
    <button @click="extractText">提取文字</button>
    <div v-if="extractedText">{{ extractedText }}</div>
  </div>
</template>

<script>
import pdfjsLib from 'pdfjs-dist'

export default {
  data () {
    return {
      selectedFile: null,
      extractedText: ''
    }
  },
  methods: {
    handleFileChange (event) {
      this.selectedFile = event.target.files[0]
    },
    async extractText () {
      if (!this.selectedFile) {
        alert('请选择一个 PDF 文件。')
        return
      }
      try {
        const loadingTask = pdfjsLib.getDocument(URL.createObjectURL(this.selectedFile))
        const pdf = await loadingTask.promise
        let textContent = ''
        for (let i = 1; i <= pdf.numPages; i++) {
          const page = await pdf.getPage(i)
          const textContentObj = await page.getTextContent()
          textContent += textContentObj.items.map(item => item.str).join(' ')
        }
        this.extractedText = textContent
      } catch (error) {
        console.error('提取文字时出错:', error)
        alert('提取文字时出现错误，请重试。')
      }
    }
  }
}
</script>
